// 上传文件需要的配置
import { UploadFile } from 'antd/es/upload';
import { createMinioClient, fileToStream } from 'tz-minio-upload_beta';
const minioBucket = 'iot';
// const stream = require('stream');
// 你的minio配置信息
const minioClient = createMinioClient({
  endPoint: 'www.67934.cn', // 地址
  port: 32011, // 端口号，若地址为类似test.minio.com,就不必写端口号
  useSSL: false, // 是否使用ssl
  accessKey: 'OKw3bxT5me', // 登录的accessKey
  secretKey: 'AnI22zu!vu89FaJ', // secretKey
});

function putObject(file: UploadFile): Promise<string> {
  return new Promise((resolve) => {
    fileToStream(file, (res: any) => {
      let metadata = {
        'content-type': file.type,
        'content-length': file.size,
      };
      minioClient.putObject(minioBucket, file.name, res, file.size, metadata, function (err: any) {
        if (err) {
          resolve('');
        } else {
          // /iot/RBC531/areaType/
          const url = `/iot/${file.name}`;
          console.log('上传成功 :>> ', file);
          resolve(url);
        }
      });
    });
  });
}

export function uploadFiles(file: UploadFile): Promise<string> {
  return new Promise((resolve) => {
    minioClient.bucketExists(minioBucket, function (err: any, exists: any) {
      if (err) {
        console.log('err :>> ', err);
        resolve('');
      }
      if (exists) {
        putObject(file).then((res) => {
          resolve(res);
        });
      } else {
      }
    });
  });
}
